// store/index.js
import { createStore } from 'vuex';

const store = createStore({
    state() {
        return {
            socketTask: null,
			reconnect: true,
			reconnectStatus: false
        };
    },
    mutations: {
        WEBSOCKET_INIT (state, url) {
			state.reconnect = true
            state.socketTask = uni.connectSocket({
                url,  // url是websocket连接ip
                success () {
                    console.log('websocket连接成功')
                }
            })
            state.socketTask.onOpen((res) => {
                console.log('WebSocket连接正常打开中...！')
                // 注：只有连接正常打开中 ，才能正常收到消息
                state.socketTask.onMessage(res => {
                    console.log('收到服务器内容：' + res.data)
                });
            })
			state.socketTask.onClose(() => {
			    console.log('WebSocket连接已关闭');
			    // Start reconnection when WebSocket is closed
			    if (state.reconnect) {
					console.log('重新连接')
					state.reconnectStatus = true
			        state.socketTask = uni.connectSocket({
			            url,  // url是websocket连接ip
			            success () {
							state.reconnectStatus = false
			                console.log('websocket连接成功')
			            }
			        })
			    }
			});
        },
        WEBSOCKET_SEND (state, data) {
            state.socketTask.send({
                data,
                async success() {
                    console.log('消息发送成功')
                },
            })
        },
        CLOSE_SOCKET (state) {
            if (!state.socketTask) return
			state.reconnect = false
            state.socketTask.close({
                success (res) {
                    console.log('关闭成功', res)
                },
                fail (err) {
                    console.log('关闭失败', err)
                }
            })
        }
    },
	actions: {
		WEBSOCKET_INIT({
		            commit
		                       }, url) {
		            commit('WEBSOCKET_INIT', url)
		        },
		        WEBSOCKET_SEND({
		            commit
		                       }, data) {
		            commit('WEBSOCKET_SEND', data)
		        },
		        CLOSE_SOCKET({
		            commit
		                     }) {
		            commit('CLOSE_SOCKET')
		        }
		
	}
		
});

export default store;
